<?php

class Fishpig_Wordpress_Helper_Post extends Fishpig_Wordpress_Helper_Abstract
{
	
	/**
	 * Returns the permalink structure stored in the WP database
	 *
	 * @return string
	 */
	public function getPermalinkStructure()
	{
		if (!$this->useGuidLinks()) {
			return ltrim($this->getCachedWpOption('permalink_structure'), ' /');
		}
		
		return false;
	}

	/**
	 * Gets the WP permalink structure from the WP database
	 * Result is split by / and returned as an array
	 * If an empty array is returned, using default ?p={{post_id}} links
	 *
	 * @return array
	 */	
	public function getExplodedPermalinkStructure()
	{
		if ($structure = $this->getPermalinkStructure()) {
			return array_filter(explode('/', $structure));
		}
		
		return false;
	}
	
	/**
	 * Returns TRUE is ?p=id links are being used
	 *
	 * @return bool
	 */
	public function useGuidLinks()
	{
		return !trim($this->getCachedWpOption('permalink_structure'), '/ -');
	}
	
	public function getFullPermalinkStructure()
	{
		if (!isset($this->_cache['options']['full_permalink_structure'])) {
			
			if ($this->useGuidLinks()) {
				$this->_cache['options']['full_permalink_structure'] = array();
			}
			else {
				$structure = $this->getPermalinkStructure();
				$parts = preg_split("/(\/)/", $structure, -1, PREG_SPLIT_DELIM_CAPTURE);
				$structure = array();

				foreach($parts as $part) {
					if ($result = preg_split("/(%[a-zA-Z0-9]{1,}%)/", $part, -1, PREG_SPLIT_DELIM_CAPTURE)) {
						$results = array_filter(array_unique($result));
						
						foreach($results as $result) {
							array_push($structure, $result);
						}
					}
					else {
						$structure[] = $part;
					}

				}

				$this->_cache['options']['full_permalink_structure'] = $structure;
			}
		}
		
		return $this->_cache['options']['full_permalink_structure'];
	}

    /**
     * return the  permalink based on permalink structure
     * which is defined in WP Admin
     *
     * @param Fishpig_Wordpress_Model_Post
     * @return string
     */
	public function getPermalink(Fishpig_Wordpress_Model_Post $post)
	{
		if (!isset($this->_cache['permalink']['post'][$post->getId()])) {
			if ($this->useGuidLinks()) {
				//$this->_cache['permalink']['post'][$post->getId()] = $this->getUrl('?p='.$post->getId());
				$this->_cache['permalink']['post'][$post->getId()] = $this->getUrl()."p{$post->getId()}.html";
			}
			else {
				$structure = $this->getFullPermalinkStructure();

				if (count($structure) > 0) {
					$url = array();
		
					foreach($structure as $segment) {
						switch($segment) {
							case '%year%':				$url[] = $post->getPostDate('Y');		break;
							case '%monthnum%':		$url[] = $post->getPostDate('m');		break;
							case '%day%':					$url[]  = $post->getPostDate('d');		break;
							case '%hour%':				$url[]  = $post->getPostDate('H');	break;
							case '%minute%':			$url[]  = $post->getPostDate('i');		break;
							case '%second%':			$url[]  = $post->getPostDate('s');		break;
							case '%postname%':		$url[] = $post->getPostName();		break;
							case '%post_id%':			$url[] = $post->getId();					break;
							case '%category%':			$url[] =$this->_getPermalinkCategoryPortion($post);	break;
							default:
								if (strlen(trim($segment, '%')) == (strlen($segment)-2)) {
									$this->log("Unknown URI token in permalink structure: '{$segment}'");
								}
								else {
									$url[] = $segment;
								}
								
								break;
						}
					}
		
					$this->_cache['permalink']['post'][$post->getId()] = $this->getUrl(implode('', $url));
				}
			}
		}
		
		return $this->_cache['permalink']['post'][$post->getId()];
	}

	/**
	 * Generates the category portion of the URL for a post
	 *
	 * @param Fishpig_Wordpress_Model_Post $post
	 * @return string
	 */
	protected function _getPermalinkCategoryPortion(Fishpig_Wordpress_Model_Post $post)
	{
		if ($category = $post->getParentCategory()) {
			return trim($category->getSlug(), '/');
		}
	}

	/**
	 * Loads a post model based on the URI (array)
	 *
	 * @param string|array $explodedUri
	 * @return FIshpig_Wordpress_Model_Post
	 */	
	public function loadByPermalink($explodedUri)
	{
		if ($this->useGuidLinks()) {
			/*add by ken. start 1*/
			if( !empty( $explodedUri ) ){
				if( isset( $explodedUri[0] ) && eregi('^p[0-9]+',$explodedUri[0]) ){
					preg_match_all('/^p([0-9]*)\.html/i',$explodedUri[0],$result);					
					return Mage::getModel('wordpress/post')->load($result[1][0]);
				}	
			}
			/*add by ken. end 1*/
			return Mage::getModel('wordpress/post')->load($this->getParam('p', 0));
		}
		
		if (!is_array($explodedUri)) {
			$explodedUri = explode('/', trim($explodedUri, '/'));
		}
		
		$structure = $this->getExplodedPermalinkStructure();

		if ((isset($explodedUri[0])) && $explodedUri[0] == $this->getBlogRoute()) {
			array_shift($explodedUri);
		}

		if (count($structure) == 0 && $postId = $this->getParam('p')) {
			$post = Mage::getModel('wordpress/post')->load($postId);
			
			if ($post->getId() > 0) {
				return $post;
			}
		}
		else if (count($structure) == count($explodedUri)) {
			$postDate = array();
			$posts = Mage::getResourceModel('wordpress/post_collection')->addIsPublishedFilter();
			$regSegment = "\%[a-zA-Z0-9]{1,}\%";
			$regToken = "([a-zA-Z0-9 -.]{1,})";

			foreach($structure as $key => $segment) {
				if (preg_match("/{$regToken}{$regSegment}|{$regSegment}{$regToken}/", $segment, $results)) {
					array_shift($results);
					$results = array_filter($results);
					
					foreach($results as $result) {
						$segment = str_replace($result, '', $segment);
						$explodedUri[$key] = str_replace($result, '', $explodedUri[$key]);
					}
				
				}

				switch($segment) {
					case '%year%':					$postDate['1, 4'] = $explodedUri[$key];									break;
					case '%monthnum%':			$postDate['6, 2'] = $explodedUri[$key];									break;
					case '%day%':						$postDate['9, 2']  = $explodedUri[$key];									break;
					case '%hour%':					$postDate['12, 2']  = $explodedUri[$key];									break;
					case '%minute%':				$postDate['15, 2']  = $explodedUri[$key];									break;
					case '%second%':				$postDate['18, 2']  = $explodedUri[$key];									break;
					case '%postname%':			$posts->addFieldToFilter('post_name', $explodedUri[$key]);	break;
					case '%post_id%':				$posts->addFieldToFilter('ID', $explodedUri[$key]);					break;
					case '%category%':				$posts->addCategorySlugFilter($explodedUri[$key]);				break;
				}
			}

			if (count($postDate) > 0) {
				$sql = array();
				
				foreach($postDate as $offsets => $value) {
					$sql[] = $this->_helper('db')->getWordpressRead()->quoteInto("SUBSTRING(post_date, {$offsets}) = ?", $value);;
				}
			
				$posts->getSelect()->where(implode(' AND ' , $sql));
			}

			if ($posts->count() > 0) {
				return $posts->getFirstItem();
			}
		}

		return false;
	}
	
	public function getTagsUrl()
	{
		return $this->getUrl('tags');
	}

}
